<!-- 藏品管理 -->
<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  NInput,
  NSelect,
  NSpace,
  NTreeSelect,
  NModal,
  NTooltip,
  NTag,
  NScrollbar,
  NEllipsis,
  
  type SelectOption,
  type DataTableColumns,
} from 'naive-ui'
import { h, ref, reactive, watch, type VNode, onMounted, onBeforeUnmount } from 'vue'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import useFlush from '@/hooks/useFlush'
const message = useMessage()
const emit = defineEmits(['update'])
const form = reactive({
  itemName: null,
  assetCode: null, //馆藏码
  collectTypeCode: null, //征集方式
  catalogStatusCode: null, //编目状态
  locationCode: null, //批次
  collectStatusCode: null, //批次
  storageStatusCode: null, //入藏状态
  itemTypeCode: null, //版本
  destinationStatusCode: null, //去向
  lableThing: null, //标签
  sourceName: null, //来源
  recipient:null, //领取人
  serialNumber: null, //流水号
  collectionTag: null, //藏品标签
})
const renderOption = ref(({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })
)
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    type: 'selection',
    disabled(row: any) {
      return row.storageStatusName === '未入藏'
    },
    width:'2rem',
  },
  {
    title: '流水号',
    key: 'serialNumber',
    align: 'center',
    width:'7rem',
  },
  {
    title: '馆藏码',
    key: 'assetCode',
    align: 'center',
    width:'11rem',
  },
  {
    title: '藏品名称',
    key: 'itemName',
    width:'10rem',
  },
  {
    title: '类型',
    key: 'itemTypeName',
    width:'5rem',
  },
  {
    title: '藏品标签',
    key: 'collectionTag',
    width:'8rem',
    render: (e:any) => {
      if (!e.collectionTag) return ''
      const items = e.collectionTag.split(',').map((m:any) => {
        return h(
          NEllipsis,
          {
            style: {
              width: '80px',
              display: 'inline-block',
              height: '30px',
              lineHeight: '30px',
              textAlign: 'center',
              padding: '0 5px',
              backgroundColor: '#3399ff',
              color: '#fff'
            }
          },
          {
            default: () => m
          }
        )
      })
      return h(
        'div',
        {
          style: {
            display: 'flex',
            flexWrap: 'wrap',
            gap: '5px'
          }
        },
        items
      )
    }
  },
  {
    title: '第一责任者',
    key: 'firstPersonResponsible',
    width:'7rem',
  },
  {
    title: '来源',
    key: 'sourceName',
    width:'5rem',
  },
  {
    title: '征集方式',
    key: 'collectTypeName',
    align: 'center',
    width:'5rem',
  },
  {
    title: '藏品状态',
    key: 'collectionStatusName',
    align: 'center',
    width:'5rem',
  },
  {
    title: '版本',
    key: 'version',
    width:'5rem',
  },
  {
    title: '库房位置',
    key: 'positionName',
    width:'7rem',
  },
  {
    title: '去向',
    key: 'destinationStatusName',
    align: 'center',
    width:'5rem',
  },
  {
    title: '领取人',
    key: 'recipient',
    width:'5rem',
  }
]
const treeLevel = ref(null)
const reset = () => {
  form.itemTypeCode = null
  form.destinationStatusCode = null
  form.itemName = null
  form.assetCode = null
  form.serialNumber = null
  form.sourceName = null
  form.recipient = null
  form.collectionTag = null
  form.collectStatusCode = null
  form.storageStatusCode = null
  form.catalogStatusCode = null
  form.locationCode = null
  treeLevel.value = null
  form.collectTypeCode = null
}
//筛选条件
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    queryTableData(true)
  }
})
const piciList = ref()
// 字典下拉
const codeFn = async (code: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: code
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data?.map((it: any) => {
    return { value: it.dicCode, label: it.dicName }
  })
}
const labelOptions = ref([])
const getLabelOptions = async () => {
  const [error, res] = await sendRequest({
    module: 'labelConfig',
    api: 'listOptions',
    override: {
      params: {
        tagUseCode: 'A6902'
      }
    }
  })
  if (error) return message.error(error.message)
  labelOptions.value = res?.data
}
const banbenList = ref()
const collectFactionList: any = ref()
const roomList: any = ref()
onBeforeUnmount(() => {dataListSelections.value = [];choiceItems.value = []})
//多选框勾选
type DataListSelectionsItem = {
  id: string
}
const deleteKeys = ref()
const dataListSelections: any = ref<DataListSelectionsItem[]>([])
const choiceItems:any = ref([])
const handleDeleteContact = (index: number,item:any) => {
  choiceItems.value.splice(index, 1)
  dataListSelections.value = choiceItems.value.map((it: any) => it.id)
  emit('update',choiceItems.value)
}
function selectionChangeHandle(val: any, info: any, action: any) {
  console.log(val, info, action.row, action.action, '多选')
  if (['check', 'checkAll'].includes(action.action)) {
    //新增
    
    if (action.action == 'checkAll') {
      
      tableData.value?.map((it: any) =>{
        if(choiceItems.value.filter((im:any)=>im.id==it.id).length==0){
          choiceItems.value.push({...it})
      }} )
      
    } else {
      choiceItems.value = [...choiceItems.value, {id: action.row?.id,itemName:action.row?.itemName}]
    }
  } else {
    //移除
    if (action.action == 'uncheckAll') {
      let temp:any = []
      let ids= tableData.value.map((it:any)=>it.id)
      choiceItems.value.map((it:any)=>{
        if(!ids.includes(it.id)){
          temp.push({...it})
        }
      })
      choiceItems.value = temp
      console.log(choiceItems.value)
    } else {
      let temp:any = []
      choiceItems.value.map((it:any)=>{
        if(action.row.id!=it.id){
          temp.push({...it})
        }
      })
      choiceItems.value= temp
    }
  }
  emit('update',choiceItems.value)
  dataListSelections.value = choiceItems.value.map((it:any)=>it.id)
}

//表格数据
const tableLoading = ref(false)
const tableData: any = ref()
const queryTableDataBefore = () => {
  queryTableData(true)
}

const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  // dataListSelections.value = []
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'collectingItemslist',
    override: {
      params: {
        ...form,
        positionLevel: treeLevel.value,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        listType: 3, //1 初编 编目 2 编目审核 3 藏品
      }
    }
  })
  if (error) return message.error(error.message)
  const tmp: any = res.data
  tableData.value = tmp?.list
  paginationReactive.itemCount = tmp.totalCount
  tableLoading.value = false
}
onMounted(async () => {
  await queryTableData()
  getTreeSelect()
  getLabelOptions()
  codeFn('A36', statusList30) //去向,关联字典A36
  await getFirstFn(0, roomList)
  codeFn('A47', piciList) //藏品状态A47
  codeFn('A30', collectFactionList) //征集方式A30
})
const statusList30 = ref()
const getTreeSelect = async () => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listTreeAll',
    override: {
      params: {
        statusCode: 'A4901'
      }
    }
  })
  if (error) return message.error(error.message)
  banbenList.value = res.data
}

const changeTree = (value: any, options: any) => {
  treeLevel.value = options?.positionLevel
  form.locationCode = value
  return
}
const handleLoad = async (option: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listOptionsAndLevelByParentId',
    override: {
      params: {
        parentId: option.value
      }
    }
  })

  if (error) return message.error(error.message) && undefined
  if (res.code !== 0) return message.error(res.msg) && undefined
  if (res.data.length === 0) {
    option.isLeaf = true
    return
  }
  // @ts-ignore
  res.data.forEach((e) => (e.isLeaf = false))
  option.children = res.data as any[]
}
// 库房位置
const getFirstFn = async (id: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listOptionsAndLevelByParentId',
    override: {
      params: {
        parentId: id
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value =
    res?.data.map((it: any) => {
      return { ...it, isLeaf: false, depth: 1 }
    }) || []
}

</script>

<template>
  <div style ='width:100%'>
  <TableView class="table">
    <template #form>
      <div>
        
        <NSpace justify="start">
          <NForm
            :show-feedback="false"
            label-placement="left"
            label-width="78px"
            @keydown.enter.prevent="queryTableData()"
          >
            <NSpace style="margin-bottom: 10px">
              <NFormItem label="藏品名称:">
                <NInput
                  placeholder="请输入藏品名称"
                  v-model:value="form.itemName"
                  style="width: 177px"
                />
              </NFormItem>
              <NFormItem label="馆藏码:">
                <NInput
                  placeholder="请输入馆藏码"
                  style="width: 177px"
                  v-model:value="form.assetCode"
                />
              </NFormItem>
              <NFormItem label="流水号:">
                <NInput
                  placeholder="请输入流水号"
                  style="width: 177px"
                  v-model:value="form.serialNumber"
                />
              </NFormItem>
             
              <NFormItem label="版本类型:">
                <n-tree-select
                  :options="banbenList"
                  children-field="childList"
                  key-field="classificationCode"
                  label-field="classificationName"
                  v-model:value="form.itemTypeCode"
                  :render-option="renderOption"
                  placeholder="请选择版本类型"
                  clearable
                  filterable
                  style="width: 177px"
                />
              </NFormItem>
              <NFormItem label="征集方式:">
                <NSelect
                  :options="collectFactionList"
                  v-model:value="form.collectTypeCode"
                  placeholder="请选择征集方式"
                  clearable
                  filterable
                  style="width: 177px"
                />
              </NFormItem>
              <NFormItem label="藏品状态:">
                <NSelect
                  :options="piciList"
                  v-model:value="form.collectStatusCode"
                  placeholder="请选择藏品状态"
                  clearable
                  filterable
                  style="width: 177px"
                />
              </NFormItem>
              <!-- 第二行 -->
              <NFormItem
                label="去向"
                path="destinationStatusCode"
              >
                <NSelect
                  :options="statusList30"
                  v-model:value="form.destinationStatusCode"
                  placeholder="请选择去向"
                  clearable
                  style="width: 177px"
                />
              </NFormItem>
              <NFormItem label="库房位置:">
                <n-tree-select
                  v-model:value="form.locationCode"
                  :options="roomList"
                  check-strategy="all"
                  :show-path="false"
                  key-field="value"
                  :allow-checking-not-loaded="true"
                  style="width: 177px"
                  placeholder="请选择类型"
                  :on-load="handleLoad"
                  clearable
                  :on-update:value="changeTree"
                />
              </NFormItem>
              <NFormItem label="来源:">
                <NInput
                  placeholder="请输入藏家"
                  style="width: 177px"
                  v-model:value="form.sourceName"
                />
              </NFormItem>

              <NFormItem
                label="藏品标签"
                path="collectionTag"
              >
                <NSelect
                  :options="labelOptions"
                  v-model:value="form.collectionTag"
                  placeholder="请选择藏品标签"
                  clearable
                  style="width: 177px"
                />
              </NFormItem>
              <NSpace>
              <NFormItem>
                <NButton
                  type="primary"
                  style="width: 78px"
                  ghost
                  @click="queryTableDataBefore()"
                >
                  查询
                </NButton>
              </NFormItem>
              <NFormItem>
                <NButton
                  style="width: 78px; "
                  ghost
                  type="primary"
                  @click="reset()"
                >
                  重置
                </NButton>
              </NFormItem>
          </NSpace>
            </NSpace>
          </NForm>
        </NSpace>
      </div>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        min-height="300px"
        :loading="tableLoading"
        :checked-row-keys="dataListSelections"
        @update:checked-row-keys="selectionChangeHandle"
      />
    </template>

    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
        <div style= 'margin-bottom:10px'>
            已选藏品
          </div>
        <NScrollbar style="min-height: 150rem;max-height:150rem;width:100%">
              <div
                v-show="choiceItems?.length"
                class="contacts-content"
              >
                <NTag
                  v-for="(contact, index) in choiceItems"
                  @close="handleDeleteContact(index,contact)"
                  :key="index"
                  :color="{ color: '#ffffff' }"
                  closable
                  style="justify-content: space-between; gap: 0 10rem"
                >

                  <NEllipsis style='width:300px'> {{ contact.itemName }}</NEllipsis>

                </NTag>
              </div>
            </NScrollbar>
</div>
</template>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 0;
  .link_content {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10rem;
  }

  .link_item {
    width: 175rem;
    height: 68rem;
    background: #e6e6e6;
    border-radius: 6rem;
    border: 1rem solid #ececec;
    display: flex;
    align-items: center;
    padding-left: 5rem;
    text-decoration: none;
    color: initial;
  }

  img {
    display: block;
    width: 35rem;
    height: 35rem;
    border-radius: 50%;
  }
}
.contacts-content {
  width: 100%;
    display: grid;
    grid-template-columns: repeat(4, minmax(300px, 2fr)) ;
    gap: 10rem;
    padding: 15rem;
    background-color: #fff;
  }
.link_item1 {
  width: 255rem;
  height: 68rem;
  background: #e6e6e6;
  border-radius: 6rem;
  border: 1rem solid #ececec;
  display: flex;
  align-items: center;
  padding-left: 5rem;
  text-decoration: none;
  color: initial;
}
</style>
